{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "40ded5cc",
   "metadata": {},
   "source": [
    "很好 👍，我来帮你梳理一下 \\*\\*DCF（现金流折现法）\\*\\*的计算逻辑，并用 Python 给你写一个框架。\n",
    "\n",
    "---\n",
    "\n",
    "# 📌 一、DCF 的核心公式\n",
    "\n",
    "企业价值（EV） = 未来自由现金流（FCF）的折现和 + 终值（Terminal Value）的折现\n",
    "\n",
    "$$\n",
    "EV = \\sum_{t=1}^{n} \\frac{FCF_t}{(1+WACC)^t} + \\frac{TV}{(1+WACC)^n}\n",
    "$$\n",
    "\n",
    "其中：\n",
    "\n",
    "* $FCF_t$：第 t 年的自由现金流\n",
    "* $WACC$：加权平均资本成本（折现率）\n",
    "* $TV$：终值（通常用永续增长模型计算）\n",
    "\n",
    "$$\n",
    "TV = \\frac{FCF_{n+1}}{WACC - g}\n",
    "$$\n",
    "\n",
    "---\n",
    "\n",
    "# 📌 二、需要的变量及说明\n",
    "\n",
    "1. **FCF（Free Cash Flow，自由现金流）**\n",
    "\n",
    "   * 定义：企业经营现金流扣除维持业务所需资本支出后的现金流\n",
    "   * 公式（简化版）：\n",
    "\n",
    "     $$\n",
    "     FCF = EBIT \\times (1 - 税率) + 折旧摊销 - 资本支出 - 营运资本增加\n",
    "     $$\n",
    "\n",
    "2. **预测期长度（n）**\n",
    "\n",
    "   * 一般取 **5\\~10 年**，过长不确定性太大\n",
    "\n",
    "3. **折现率（WACC）**\n",
    "\n",
    "   * 加权平均资本成本：\n",
    "\n",
    "     $$\n",
    "     WACC = \\frac{E}{D+E} \\times Ke + \\frac{D}{D+E} \\times Kd \\times (1 - 税率)\n",
    "     $$\n",
    "\n",
    "     * E：股权价值\n",
    "     * D：债务价值\n",
    "     * Ke：股权成本（常用 CAPM 模型估算）\n",
    "     * Kd：债务成本（利息率）\n",
    "\n",
    "4. **永续增长率（g）**\n",
    "\n",
    "   * 终值部分的增长率，一般设为 **长期经济增速或行业平均增速**（如 2%\\~3%）\n",
    "\n",
    "5. **净债务（Net Debt）**\n",
    "\n",
    "   * 企业价值 EV 减去净债务 = 股权价值\n",
    "   * 股权价值 ÷ 股数 = 每股价值\n",
    "\n",
    "---\n",
    "\n",
    "要不要我帮你加一个 **敏感性分析**（比如不同 WACC、增长率 g 下，每股价值的变化），这样你能看出估值区间而不是单一结果？\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67d9a7ac",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "预测期自由现金流： ['904.19亿', '931.31亿', '959.25亿']\n",
      "折现自由现金流： ['837.21亿', '798.45亿', '761.48亿']\n",
      "终值： 1.98万亿  折现后： 1.57万亿\n",
      "企业价值 EV： 1.81万亿\n",
      "股权价值 Equity Value： 1.81万亿\n",
      "每股合理价值： 1439.79\n"
     ]
    }
   ],
   "source": [
    "import akshare as ak\n",
    "import pandas as pd\n",
    "\n",
    "# ========== 参数设置 ==========\n",
    "symbol = \"600519\"             # 股票代码\n",
    "forecast_years = 5            # 预测期（年数）\n",
    "r = 0.08                       # 折现率（WACC）\n",
    "g = 0.03                      # 永续增长率\n",
    "shares_outstanding =  12.56 * 10000 * 10000  # 总股本（股）\n",
    "\n",
    "# ========== 获取现金流量表 ==========\n",
    "df = ak.stock_financial_cash_ths(symbol=symbol, indicator=\"按年度\")\n",
    "\n",
    "# 提取需要的字段\n",
    "df_fcf = df[[\"报告期\", \"经营活动产生的现金流量净额\", \"购建固定资产、无形资产和其他长期资产支付的现金\"]].copy()\n",
    "\n",
    "# ========== 数据清洗函数 ==========\n",
    "def to_num(x):\n",
    "    if isinstance(x, str):\n",
    "        x = x.replace(\",\", \"\")  # 去掉千分符\n",
    "        x = x.replace(\"(\", \"-\").replace(\")\", \"\")  # (123) 转成 -123\n",
    "        if \"亿\" in x:\n",
    "            return float(x.replace(\"亿\", \"\")) * 1e8\n",
    "        elif \"万\" in x:\n",
    "            return float(x.replace(\"万\", \"\")) * 1e4\n",
    "    try:\n",
    "        return float(x)\n",
    "    except:\n",
    "        return None\n",
    "\n",
    "for col in [\"经营活动产生的现金流量净额\", \"购建固定资产、无形资产和其他长期资产支付的现金\"]:\n",
    "    df_fcf[col] = df_fcf[col].apply(to_num)\n",
    "\n",
    "# 计算自由现金流\n",
    "df_fcf[\"自由现金流\"] = df_fcf[\"经营活动产生的现金流量净额\"] - df_fcf[\"购建固定资产、无形资产和其他长期资产支付的现金\"]\n",
    "\n",
    "# ========== DCF 计算 ==========\n",
    "fcf_last = df_fcf.loc[0, \"自由现金流\"]\n",
    "\n",
    "fcf_list = []\n",
    "discounted_fcf = []\n",
    "\n",
    "for t in range(1, forecast_years + 1):\n",
    "    fcf_t = fcf_last * ((1 + g) ** t)\n",
    "    fcf_list.append(fcf_t)\n",
    "    discounted_fcf.append(fcf_t / ((1 + r) ** t))\n",
    "\n",
    "terminal_value = fcf_list[-1] * (1 + g) / (r - g)\n",
    "discounted_tv = terminal_value / ((1 + r) ** forecast_years)\n",
    "EV = sum(discounted_fcf) + discounted_tv\n",
    "equity_value = EV\n",
    "fair_value_per_share = equity_value / shares_outstanding\n",
    "\n",
    "# ========== 格式化函数 ==========\n",
    "def format_money(x):\n",
    "    x = float(x)\n",
    "    if abs(x) >= 1e12:\n",
    "        return f\"{x/1e12:.2f}万亿\"\n",
    "    elif abs(x) >= 1e8:\n",
    "        return f\"{x/1e8:.2f}亿\"\n",
    "    elif abs(x) >= 1e4:\n",
    "        return f\"{x/1e4:.2f}万\"\n",
    "    else:\n",
    "        return f\"{x:.2f}\"\n",
    "\n",
    "# ========== 打印结果 ==========\n",
    "print(\"预测期自由现金流：\", [format_money(x) for x in fcf_list])\n",
    "print(\"折现自由现金流：\", [format_money(x) for x in discounted_fcf])\n",
    "print(\"终值：\", format_money(terminal_value), \" 折现后：\", format_money(discounted_tv))\n",
    "print(\"企业价值 EV：\", format_money(EV))\n",
    "print(\"股权价值 Equity Value：\", format_money(equity_value))\n",
    "print(\"每股合理价值：\", format_money(fair_value_per_share))\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.0"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
